package com.wentao.mall.entity

import org.springframework.data.annotation.CreatedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import java.util.*
import javax.persistence.*

@Entity
@EntityListeners(AuditingEntityListener::class)
class Operator : UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Int = 0
    private lateinit var username: String
    private lateinit var password: String

    @Convert(converter = SetConverter::class)
    private var authorityArray: Set<Int>? = null
    private var enabled = true

    @CreatedDate
    var createdDate: Date? = null

    override fun getAuthorities(): Collection<GrantedAuthority> {
        return authorityArray?.map {
            SimpleGrantedAuthority(it.toString())
        } ?: emptyList<SimpleGrantedAuthority>()
    }

    override fun isAccountNonExpired() = true

    override fun isAccountNonLocked() = true

    override fun isCredentialsNonExpired() = true

    override fun isEnabled() = enabled

    override fun getPassword() = password

    override fun getUsername() = username

    override fun toString(): String {
        return ("UserDomain [id=" + id + ", username=" + username + ", password=" + password + ", authorityArray="
            + authorityArray + ", enabled=" + enabled + ", createdDate=" + createdDate + "]")
    }

    constructor(username: String, password: String, authorities: TreeSet<Int>) {
        this.username = username
        this.password = password
        authorityArray = authorities
        enabled = true
    }

    constructor(username: String, password: String, vararg authorities: Int) {
        this.username = username
        this.password = password
//        val list = TreeSet<Int>()
//        for (i in authorities.indices) {
//            list.add(i)
//        }
        authorityArray = authorities.toSet()
        enabled = true
    }
}